package org.fzu.ercha.wuta.Service;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;

import org.fzu.ercha.wuta.Entity.Audio;
import org.fzu.ercha.wuta.MyApplication;
import org.fzu.ercha.wuta.Util.LogUtil;

import java.io.IOException;

/**
 * Created by ercha on 2017/1/26.
 */

public class MainService extends Service
        implements MediaPlayer.OnErrorListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener{

    public static class State {
        public static final int
                IDLE = 0,
                INITIALIZED = 1,
                PREPARED = 2,
                PREPARING = 3,
                STARTED = 4,
                PAUSED = 5,
                STOPPED = 6,
                COMPLETED = 7,
                END = -1,
                ERROR = -2;
    }

    private String className = getClass().getName();

    private MediaPlayer mMediaPlaer;
    private int mCurrentState;

    private OnPlaybackListener mPlaybackListener = null;

    public static class ServiceBinder extends Binder {

        private MainService mService = null;

        public ServiceBinder(MainService service) {
            mService = service;
        }

        public MainService getService () {
            return mService;
        }
    }

    /**
     * 服务创建时调用
     */
    @Override
    public void onCreate(){
        super.onCreate();

        mMediaPlaer = new MediaPlayer();
        changeState(State.IDLE);

        mMediaPlaer.setOnErrorListener(this);		//MainService 要实现这三个接口
        mMediaPlaer.setOnPreparedListener(this);
        mMediaPlaer.setOnCompletionListener(this);

    }

    @Override
    public IBinder onBind(Intent intent) {
        return new ServiceBinder(this);
    }

    /**
     * 每次服务启动时调用
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return Service.START_STICKY;
        //return super.onStartCommand(intent, flags, startId);
    }



    //这个方法用来初始化我们的MediaPlayer
    private void init () {
//        if (mMediaPlaer == null) {
//            mMediaPlaer = new MediaPlayer();
//            changeState(State.IDLE);
//
//            mMediaPlaer.setOnErrorListener(this);		//MainService 要实现这三个接口
//            mMediaPlaer.setOnPreparedListener(this);
//            mMediaPlaer.setOnCompletionListener(this);
//        } else {
//            if (mCurrentState == State.IDLE || mCurrentState == State.INITIALIZED || mCurrentState == State.PREPARED ||
//                    mCurrentState == State.STOPPED ||
//                    mCurrentState == State.COMPLETED || mCurrentState == State.ERROR) {
//                mMediaPlaer.reset();
//                changeState(State.IDLE);		//注意状态更改的代码
//            }
//
//        }
    }

    /**
     *
     */
    public void start(){
        if(mCurrentState == State.PAUSED){
            //如果是暂停时调用，则继续播放
            mMediaPlaer.start();
            changeState(State.STARTED);
        } else {
            //如果是刚进入应用调用的话
            start(MyApplication.getCurrentAudio());
        }
    }

    /**
     * 用于切换歌曲
     * @param audio
     */
    public void start (Audio audio) {
        if(audio == null){
            return;
        }
        try {
            if(mCurrentState != State.IDLE){
                mMediaPlaer.reset();
                changeState(State.IDLE);
            }
            mMediaPlaer.setDataSource(this, audio.getUri());    //Valid Sates IDLE
            mMediaPlaer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlaer.prepareAsync();//Valid Sates{Initialized, Stopped}
            changeState(State.PREPARING);
//            switch (mCurrentState){
//                case State.PREPARING:
//                case State.COMPLETED:
//                case State.STOPPED:
//                    mMediaPlaer.reset();
//                    changeState(State.IDLE);
//                    //fall...
//
//                //播放某首歌
//                case State.IDLE:
//                    mMediaPlaer.setDataSource(this, audio.getUri());    //Valid Sates IDLE
//                    mMediaPlaer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//                    mMediaPlaer.prepareAsync();//Valid Sates{Initialized, Stopped}
//                    changeState(State.PREPARING);
//                    break;
//
//                //继续播放
//                case State.PAUSED:
//                    mMediaPlaer.start();
//                    break;
//            }
//            if (mCurrentState == State.IDLE) {
//                mMediaPlaer.setDataSource(this, audio.getUri());    //Valid Sates IDLE
//                changeState(State.INITIALIZED);
//            }
//            if (mCurrentState != State.ERROR) {
//                mMediaPlaer.setAudioStreamType(AudioManager.STREAM_MUSIC);      //Invalid States ERROR
//            }
//            if (mCurrentState == State.INITIALIZED || mCurrentState == State.STOPPED) {
//                mMediaPlaer.prepareAsync();//Valid Sates{Initialized, Stopped}
//                changeState(State.PREPARING);
//            }
//            if (mCurrentState == State.PAUSED){
//                mMediaPlaer.start();
//            }
        } catch (IOException e) {
            LogUtil.e(e.toString());
        }
    }

    public void last(){
        start(MyApplication.getLastAudio());
        MyApplication.toLastAudio();
    }

    public void next(){
        start(MyApplication.getNextAudio());
        MyApplication.toNextAudio();
    }

    public void pause(){
        if(mCurrentState != State.STARTED){
            return;
        }
        mMediaPlaer.pause();
        changeState(State.PAUSED);
    }

    /**
     * 秒为单位
     * @return
     */
    public int getCurrentPosition(){
        return mMediaPlaer.getCurrentPosition() / 1000;
    }

    /**
     * 秒为单位
     * @return
     */
    public int getDuration(){
        return mMediaPlaer.getDuration() / 1000;
    }

    /**
     * 秒为单位
     * @return
     */
    public void seekTo(int ss){
        mMediaPlaer.seekTo(ss * 1000);
    }

    public Audio getCurrentAudio(){
        return MyApplication.getCurrentAudio();
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        LogUtil.i(className, "here onCompletion!");
        changeState(State.COMPLETED);
    }

    public void onPrepared(MediaPlayer mediaPlayer){
        //准备好后就开始播放
        LogUtil.i(className, "here onPrepared!");
        mMediaPlaer.start();
        changeState(State.STARTED);
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        // ... react appropriately ...
        LogUtil.e("MainService", what + "");
        // The MediaPlayer has moved to the Error state, must be reset!
        changeState(State.IDLE);
        return true;
    }

    private void changeState (int state) {
        mCurrentState = state;
        if (mPlaybackListener != null) {
            mPlaybackListener.onStateChanged(mCurrentState);
        }
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        mMediaPlaer.release();
    }

    public void setOnPlaybackListener (OnPlaybackListener listener) {
        mPlaybackListener = listener;
    }

    public interface OnPlaybackListener {
        void onStateChanged (int state);
    }
}
